package SynchAndCopyRealize;

import java.util.HashMap;
import java.util.Map;


public class MonitorVehicleTracker {

        private final Map<String, MutablePoint> locations;

        public MonitorVehicleTracker(Map<String, MutablePoint> data) {
                locations = deepCopy(data);
        }

        public synchronized MutablePoint getLocation(String name) {
                MutablePoint loc = safeGetWithCopy(name);
                return new MutablePoint(loc);
        }

        public synchronized void setLocation(String name, MutablePoint point) {
                MutablePoint loc = safeGetWithCopy(name);
                loc.x = point.x;
                loc.y = point.y;
        }

        public synchronized Map<String, MutablePoint> getLocations() {
                return deepCopy(locations);
        }

        private MutablePoint safeGetWithCopy(String name) {
                MutablePoint loc = locations.get(name);
                if (loc == null)
                        throw new IllegalArgumentException("no name " + name);
                return loc;
        }

        private Map<String, MutablePoint> deepCopy(Map<String, MutablePoint> src) {
                Map<String, MutablePoint> copy = new HashMap<>();
                for (String name : src.keySet()) {
                        MutablePoint point = src.get(name);
                        copy.put(name, new MutablePoint(point));
                }
                return copy;
        }

}